package com.webListener;

/**
 * @author Mathison
 * @Title: LoginListener
 * @Package: com.webListener
 * @Description: TODO
 * @date 2021/11/20 14:35
 **/

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


public class MerchantLoginListener implements HttpSessionListener,ServletContextListener{
    private ServletContext application = null;
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("context destory");
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("context init Merchant");
        application = sce.getServletContext();
        Set<String> onlineMerchantSet = new HashSet<String>();
        Map merchantStatusMap = new HashMap();
        application.setAttribute("onlineMerchantSet", onlineMerchantSet);
        application.setAttribute("merchantStatusMap",merchantStatusMap);
    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {

        System.out.println("session create");
    }


//    退出登录时从application的onlineUserSet中删除该用户
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        Set<String> onlineMerchantSet = (Set<String>)application.getAttribute("onlineMerchantSet");
        Map merchantStatusMap = (Map)application.getAttribute("merchantStatusMap");
        String username = (String)session.getAttribute("username");
        merchantStatusMap.replace(username,1);
        onlineMerchantSet.remove(username);
        application.setAttribute("onlineMerchantSet", onlineMerchantSet);
        onlineMerchantSet = (Set<String>)application.getAttribute("onlineMerchantSet");
//        System.out.println(onlineMerchantSet.toString());
        System.out.println(username + "超时退出");
        System.out.println("session destory");
    }

}

